<template>
  <div>
    <!--    <el-card>-->
    <!--      <div slot="header" class="clearfix">-->
    <!--        <span>条件搜索</span>-->
    <!--        <div class="base-el-float-right">-->
    <!--          <el-button-group>-->
    <!--            <el-button type="primary" icon="el-icon-refresh" @click="resetForm">重置</el-button>-->
    <!--            <el-button type="primary" icon="el-icon-search" @click="submitForm">搜索</el-button>-->
    <!--          </el-button-group>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--      <el-form ref="ruleForm" :inline="true" :model="formInline">-->
    <!--        <el-form-item label="区域名称:">-->
    <!--          <el-input v-model="formInline.areaName" placeholder="请输入区域名称" />-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--    </el-card>-->

    <!-- 栏目列表 -->
    <el-card class="base-el-card-bottom">
      <div slot="header" class="clearfix">
        <span>栏目列表</span>
        <el-button class="base-el-float-right" type="primary" icon="el-icon-plus" @click="handleEdit(null)">新增</el-button>
      </div>
      <PaginationTable :table-data="tableData" :show-pagination="false">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column prop="name" label="栏目名称" />
        <el-table-column prop="description" label="栏目描述" />
        <el-table-column prop="sort" label="栏目排序" />
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | timeFormatFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否有效">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isEnable ? 'success' : 'danger'">{{ scope.row.isEnable ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
          </template>
        </el-table-column>
      </PaginationTable>

      <el-dialog title="编辑栏目" :show-close="false" :visible="dialogVisible">
        <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="dataForm.name" />
          </el-form-item>
          <el-form-item label="简介:" prop="description">
            <el-input v-model="dataForm.description" />
          </el-form-item>
          <el-form-item label="排序:" prop="sort">
            <el-input-number v-model="dataForm.sort" :min="1" :step="1" />
          </el-form-item>
          <el-form-item label="是否有效:" prop="isEnable">
            <el-switch v-model="dataForm.isEnable" />
          </el-form-item>
          <el-form-item label="产品列表:" prop="productList">
            <el-form :inline="true">
              <el-form-item>
                <el-select v-model="selectedProductId" filterable placeholder="请选择产品">
                  <el-option
                    v-for="item in productList"
                    :key="item._id"
                    :label="item.title"
                    :value="item._id"
                  />
                </el-select>
                <el-button type="primary" @click="handleProductAdd">添加</el-button>
              </el-form-item>
            </el-form>

            <PaginationTable :table-data="dataForm.productData" :show-pagination="false">
              <el-table-column label="产品图片">
                <template slot-scope="scope">
                  <el-image :src="scope.row.images[0]" :preview-src-list="scope.row.images" />
                </template>
              </el-table-column>
              <el-table-column label="产品信息" width="150">
                <template slot-scope="scope">
                  <p>评分：<b>{{ scope.row.score }}</b>分</p>
                  <p>标题：<b>{{ scope.row.title }}</b></p>
                </template>
              </el-table-column>
              <el-table-column label="产品标签">
                <template slot-scope="scope">
                  <el-tag v-for="item of scope.row.tags" :key="item" type="primary">{{ item }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="排序" prop="sort" width="60" />
              <el-table-column label="是否上架" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isEnable ? 'success' : 'danger'">{{ scope.row.isEnable ? '是' : '否' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleProductDelete(scope.row, scope.$index)">移除</el-link>
                </template>
              </el-table-column>
            </PaginationTable>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="doEdit">确认</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import PaginationTable from '@/components/PaginationTable'
import { queryByCondition, updateById, insertRecord, queryById } from '@/api/commoncrud'
const defaultFormInline = {
  areaName: ''
}
export default {
  name: 'Section',
  components: { PaginationTable },
  data() {
    return {
      formInline: {
        ...defaultFormInline
      },
      area: {},
      modelName: 'section',
      selectedProductId: '',
      productList: [],

      tableData: [],
      dataForm: {},
      rules: {
        name: [{ required: true, trigger: 'blur', message: '请输入栏目名称' }],
        description: [{ required: true, trigger: 'blur', message: '请输入栏目简介' }],
        productList: [{ type: 'array', required: true, trigger: 'change', message: '请最少设置一个商品' }]
      },
      dialogVisible: false
    }
  },
  async created() {
    this.area = JSON.parse(window.localStorage.getItem('defaultArea'))
    await this.fetchData()
    await this.fetchProductData()
  },
  methods: {
    async fetchData() {
      const query = { sort: { sort: -1 }, areaId: this.area._id }
      Object.keys(this.formInline).forEach(key => {
        if (this.formInline[key]) { query[key] = this.formInline[key] }
      })
      const res = await queryByCondition(this.modelName, 0, 1000, query)
      this.tableData = res.data.documentList
    },
    async fetchProductData() {
      const productRes = await queryByCondition('product', 0, 10000, { areaId: this.area._id })
      this.productList = productRes.data.documentList
    },
    async handleProductAdd() {
      if (!this.selectedProductId) {
        this.$message.error('请选择产品!')
        return
      }
      if (this.dataForm.productList.indexOf(this.selectedProductId) !== -1) {
        this.$message.error('该产品已添加,请重新选择!')
        return
      }
      const res = await queryById('product', this.selectedProductId)
      this.dataForm.productList.push(this.selectedProductId)
      this.dataForm.productData.push(res.data)
      this.selectedProductId = ''
    },
    handleProductDelete(data, index) {
      this.$alert('确认删除?', '消息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: action => {
          if (action === 'confirm') {
            this.dataForm.productList.splice(index, 1)
            this.dataForm.productData.splice(index, 1)
          }
        }
      })
    },
    async handleEdit(data) {
      if (data) {
        const productRes = await queryByCondition('product', 0, 1000, { _id: { $in: data.productList }, sort: { createTime: -1 }})
        const productData = productRes.data.documentList
        this.dataForm = {
          _id: data._id,
          name: data.name,
          description: data.description,
          sort: data.sort,
          isEnable: data.isEnable,
          productList: data.productList,
          productData: productData
        }
      } else {
        this.dataForm = {
          name: '',
          description: '',
          sort: 1,
          isEnable: false,
          productList: [],
          productData: []
        }
      }
      this.dialogVisible = true
    },
    handleClose() {
      this.dataForm = {}
      this.dialogVisible = false
    },
    async doEdit() {
      this.$refs['dataForm'].validate(async validate => {
        if (validate) {
          const data = this.dataForm
          const modelId = data._id
          if (modelId) {
            delete data._id
            await updateById(this.modelName, modelId, {
              name: data.name,
              description: data.description,
              sort: data.sort,
              isEnable: data.isEnable,
              productList: data.productList
            })
          } else {
            await insertRecord(this.modelName, {
              areaId: this.area._id,
              name: data.name,
              description: data.description,
              sort: data.sort,
              isEnable: data.isEnable,
              productList: data.productList
            })
          }
          this.dialogVisible = false
          this.$message.success('操作成功!')
          await this.fetchData()
        }
      })
    },

    async submitForm() {
      await this.fetchData()
    },
    async resetForm() {
      this.formInline = {
        ...defaultFormInline
      }
      await this.fetchData()
    }
  }
}
</script>

<style scoped>

</style>
